layui.use(['jquery', 'form', 'layer'], function() {
    let $ = layui.jquery;
    let form = layui.form;
    let layer = layui.layer;
    //自定义验证规则
    form.verify({

        password: [
            /^[\S]{6,12}$/, '密码必须6到12位，且不能出现空格'
        ],
        repassword: function(value) { //value：表单的值、item：表单的DOM对象
            let password = $('.password1').val();
            if (value != password) {
                return '两次密码不一致';

            }
        }
    });
    //注册登录切换
    $('#register-a').click(function() {
        document.querySelector('#login_form').style = 'display:none';
        document.querySelector('#reg_form').style = 'display:block';
    })
    $('#login-a').click(function() {
        document.querySelector('#login_form').style = 'display:block';
        document.querySelector('#reg_form').style = 'display:none';

    })
    //登录监听提交
    form.on('submit(login)', function(data) {
        let field = data.field; //获取表单数据
        $.ajax({
            method: 'POST',
            url: '/api/login',
            data: field,
            success: function(result) {
                if (result.status == 0) {
                    console.log(result);
                    localStorage.setItem('token', result.token); //储存token
                    layer.msg('登录成功', function() {

                        location.href = 'index.html'; //跳转到主页

                    })
                } 

            }

        })
        return false; //阻止表单默认提交
    });
    //注册监听提交
    form.on('submit(register)', function(data) {
        let field = data.field;
        console.log(field);
        $.post('/api/reguser', field, function(result) {
            if (result.status == 0) {
                console.log(result);
                if (result == 0) {
                    layer.msg(result.message)
                } else {
                    layer.msg(result.message)
                }
            }

        })
        return false;
    });


})
